<?php
include_once(TOOL.'Html.php');
include_once(TOOL.'Dir.php');

class Menu
{
    const targetEnd = '.html';

    public static $alias = [
        'index' => '开始',
    ];
    
    //去掉排序用的字符串
    public static function trimOrder($str)
    {
        return preg_replace('#_\d+_#i', '', $str);
    }
    
    //生成目录HTML字符串
    public static function getMenu($uniqueList, $title)
    {
        //菜单列表容器
        $menuRoot = tag::ini('div')->addClass('panel-list');
        $docTitle = p::ini()->setText($title);
        $menuRoot->append($docTitle);

        $menus = [];
        foreach ($uniqueList as $code => $node) {
            $current = self::trimOrder($node['current']);
            $current = !empty(self::$alias[$current]) ? self::$alias[$current] : $current;
            
            if ($node['is_file'] == '1') { //当前节点是最后一级的文件
                $p = p::ini()
                    ->setText($current)
                    ->setAttr('id', $code)
                    ->setAttr('onclick', 'redirect(this)')
                    ->addClass('file');
                if (!empty($node['parent'])) {
                    $menus[$code] = $p; //根目录的文件

                } else {
                    $box = tag::ini('div')->addClass('panel-box');
                    $title = tag::ini('div')->addClass('panel-title');
                    $titleName = tag::ini('div')->addClass('panel-title-name');
                    $titleName->append($p); //根目录下的文件用panel-box包一层，统一样式
                    $title->append($titleName);
                    $box->append($title, 'title');

                    $menus[$code] = $box;
                }

            } elseif (empty($menus[$code])) { //当前节点是中间目录

                $box = tag::ini('div')->addClass('panel-box')->setAttr('onclick', 'togglePanel(this)');
                $title = tag::ini('div')->addClass('panel-title');
                $titleName = tag::ini('div')->setText($current)->addClass('panel-title-name');
                $title->append($titleName);
                $body = tag::ini('div')->addClass('panel-body')->addClass('hide')->setAttr('id', $code);
                $box->append($title, 'title')->append($body, 'body');

                $menus[$code] = $box;

            }
        }

        //组装嵌套的div
        foreach ($uniqueList as $code => $node) {
            if (!empty($node['parent'])) {
                //非根目录的文件
                $menus[$node['parent']]->arrChild['body']->append($menus[$code]);
            } else {
                //根目录的文件
                $menuRoot->append($menus[$code]);
            }
        }

        return $menuRoot->out(); //返回HTML字符串
        
    }
    
}